﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using SmartCard.Framework;
using SmartCardClient.Views;
using SmartCard.Framework.CardFeatures;
using SmartCardClient.ViewModels.Features;

namespace SmartCardClient.ViewModels
{
	internal class MainViewModel : DialogViewModel
	{
		#region fields

		private ICard _selectedCard;
		private ISmartCardReaderManager _manager;
		private ObservableCollection<FeatureViewModel> _featureViewModels;

		#endregion

		#region 

		public ObservableCollection<FeatureViewModel> FeatureViewModels
		{
			get
			{ return _featureViewModels; }
			set
			{
				_featureViewModels = value;
				Changed(() => FeatureViewModels);
			}
		}

		#endregion

		#region construction

		public MainViewModel(Action closeAction)
			: base(closeAction)
		{
			_manager = new DefaultFrameworkCardReaderManager();
			SelectCardCommand = new RelayCommand<object>((x) => SelectCard());
		}

		#endregion

		#region commands

		public RelayCommand<object> SelectCardCommand
		{ get; set; }

		public RelayCommand<object> DisconnectFromCardCommand
		{ get; set; }

		#endregion

		#region Event Handlers

		private void SelectCard()
		{
			var view = new SelectCardView();
			var viewModel = new SelectCardViewModel(_manager, view.Close);
			view.DataContext = viewModel;
			view.ShowDialog();

			if (viewModel.SelectedReader != null)
			{
				var card = viewModel.SelectedReader.GetInsertedCard();
				if (card != null)
				{
					// hacky connect disconnect, but just force connect and
					// disconnect until we get some UI for it.
					if (_selectedCard != null)
					{ _selectedCard.Disconnect(new DisconnectOptions()); }
					_selectedCard = card;
					_selectedCard.Connect(new ConnectionOptions());

					LoadFeatures();
				}
			}
		}

		private void ResetCardSelection()
		{
			_selectedCard = null;
			if (FeatureViewModels != null)
			{ FeatureViewModels.Clear(); }
		}

		private void LoadFeatures()
		{
			var features = new ObservableCollection<FeatureViewModel>();

			foreach (var feature in _selectedCard.Features)
			{
				if (feature.GetType().Equals(typeof(RawCommandFeature)))
				{ features.Add(new RawApduViewModel(feature as RawCommandFeature)); }
			}

			FeatureViewModels = features;
		}

		#endregion
	}
}
